package de.preisrobot.business.parser.billiger;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;
import net.htmlparser.jericho.StartTag;

import org.apache.log4j.Logger;

import de.preiscrawler.AlleAnbieter;
import de.preisrobot.business.parser.AbstractParser;
import de.preisrobot.entity.Artikel;
import de.preisrobot.service.internal.PreisRobotParserException;

public class BilligerParser extends AbstractParser
{

   private static Logger log = Logger.getLogger(BilligerParser.class);

 
   public List<Artikel> parse(Source source) throws Exception
   {

      List<Artikel> list = new ArrayList<Artikel>();

//      if (sourceUrlString == null || sourceUrlString.length() == 0)
//         throw new RuntimeException("Using default argument of \"" + sourceUrlString + '"');
//
//       = new Source(new URL(sourceUrlString));

      List<Element> elementList = source.getAllElementsByClass("ad_listitem");

      if (elementList == null || elementList.size() == 0)
         throw new PreisRobotParserException();

      for (Element element : elementList)
      {

         try
         {
            Artikel artikel = getContent(element);
            list.add(artikel);
         }
         catch (Exception e)
         {

            log.info(" ungueltiges Element " + element.getName() + " reason:" + e.getMessage());
         }
      }

      return list;
   }

   private Artikel getContent(Element element)
   {

      List<StartTag> allStartTags = element.getFirstElement().getAllStartTags("img");// NextSibling().getFirstChild().getFirstChild().getFirstChild().getTextNode()

      String imageUrl = allStartTags.get(0).getAttributeValue("src");
      List<Element> allElements = element.getAllElements("a");

      String artikelDetialLink = allElements.get(2).getAttributeValue("href");
      String artikelKurzText = allElements.get(2).getTextExtractor().toString();

      List<Element> allElements2 = element.getAllElements("span");

      String preis = findPreisElement(allElements2);

      System.out.println(" " + artikelKurzText + " " + preis);

      Artikel a = new Artikel();
      a.setAnbieterId(AlleAnbieter.BILLIGER);
      a.setPreis(preis);
      a.setArtikelLink(artikelDetialLink);
      a.setDesc(artikelKurzText);
      a.setImageLink(imageUrl);
      // debugElements(element);

      return a;
   }

   private String findPreisElement(List<Element> allElements2)
   {
      String euro = null;
      String cent = null;
      for (Element element : allElements2)
      {
         String value = element.getAttributeValue("class");
         if (null != value)
         {

            if (value.equals("T20")) // Preis hat CSS class T20
               euro = element.getTextExtractor().toString();
            else if (value.equals("valign_top T13"))
               cent = element.getTextExtractor().toString();

         }
         if (euro != null && cent != null)
            return euro + cent;
      }
      return null;
   }

   private void debugElements(Element element)
   {
      List<Element> childElements = element.getChildElements();
      for (Element element2 : childElements)
      {
         printElement(2, element2);

         List<Element> childElements2 = element2.getChildElements();
         for (Element element3 : childElements2)
         {
            printElement(4, element3);

            List<Element> childElements3 = element3.getChildElements();
            for (Element element4 : childElements3)
            {
               printElement(6, element4);

               List<Element> childElements4 = element4.getChildElements();
               for (Element element5 : childElements4)
               {
                  printElement(8, element5);
               }
            }
         }
      }
   }

   private void printElement(int einruecken, Element element)
   {
      String leerstring = "";
      for (int i = 0; i < einruecken; i++)
         leerstring += " ";

      String name = element.getName();
      String attributeValue = element.getAttributeValue("class");
      System.out.println(leerstring + "" + name + " " + attributeValue);
   }

   private void getPrice(Element element, Artikel artikel)
   {
      element.getFirstElement();
      List<Element> allElements = element.getAllElements();
      String[] arr = new String[3];

      for (Element element2 : allElements)
      {
         String name = element2.getName();

         if (name.contains("span"))
         {
            // Sring imagePath =getImage(element2);
            String attributeValue = element2.getTextExtractor().toString();
            arr[0] = attributeValue;
         }
         else if (name.startsWith("a"))
         {
            String attributeValue = element2.getAttributeValue("href");
            String attributeValue2 = element2.getTextExtractor().toString();
            arr[1] = attributeValue;
            arr[2] = attributeValue2;
         }

      }

      artikel.setPreis(arr[0]);
      artikel.setArtikelPreisRef(arr[1]);
      artikel.setPreisDesc(arr[2]);
   }

   private void getProductLine(Element element, Artikel artikel)
   {

      Element firstElement = element.getFirstElement();
      List<Element> allElements = firstElement.getAllElements();
      String[] arr = new String[3];

      for (Element element2 : allElements)
      {
         String name = element2.getName();

         if (name.contains("img"))
         {
            // Sring imagePath =getImage(element2);
            String attributeValue = element2.getAttributeValue("src");
            arr[0] = attributeValue;
         }
         else if (name.startsWith("a"))
         {
            String attributeValue = element2.getAttributeValue("href");
            String attributeValue2 = element2.getTextExtractor().toString();
            arr[1] = attributeValue;
            arr[2] = attributeValue2;
         }

      }
      artikel.setImageLink(arr[0]);
      artikel.setArtikelLink(arr[1]);
      artikel.setDesc(arr[2]);
      System.out.println(firstElement.getName() + " " + arr[0] + " " + arr[1] + " " + arr[2]);
   }

   @Override
   public int getAnbieter()
   {
      return AlleAnbieter.BILLIGER;
   }

   @Override
   public void parseStream(List<Artikel> list, InputStream in) throws IOException, PreisRobotParserException
   {
      Source source = new Source(in);

      List<Element> elementList = source.getAllElementsByClass("ad_listitem");

      if (elementList == null || elementList.size() == 0)
         throw new PreisRobotParserException();

      for (Element element : elementList)
      {

         try
         {
            Artikel artikel = getContent(element);
            list.add(artikel);
         }
         catch (Exception e)
         {

            log.info(" ungueltiges Element " + element.getName() + " reason:" + e.getMessage());
         }
      }
   }
   
   @Override
   public void parseStream(List<Artikel> list, Reader in) throws IOException, PreisRobotParserException
   {
         List<Artikel> list2 =null;
         try
         {
            list2 = parse(new Source(in));
         }
         catch (Exception e)
         {
            e.printStackTrace();
         }
         list.addAll(list2);
   }
}
